package com.sskj.mqtt.many;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;

/**
 * @Author: Like
 * @Date: 2025/3/3 16:30
 * @Description: MqttClientTemplate: mqtt发布消息服务类
 */
@Slf4j
public class MqttClientTemplate {

    /**
     * 发布消息
     *
     * @param clientId mqtt clientId
     * @param topic    主题
     * @param msg      消息
     */
    public static void publish(String clientId, String topic, String msg) {
        MqttClientConnect mqttClientConnect = MqttClientConnect.mqttClients.get(clientId);
        try {
            mqttClientConnect.pub(topic, msg);
        } catch (MqttException e) {
            log.error("publish error", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 发布消息
     *
     * @param clientId mqtt clientId
     * @param topic    主题
     * @param msg      消息
     * @param qos      级别
     */
    public static void publish(String clientId, String topic, String msg, int qos) {
        MqttClientConnect mqttClientConnect = MqttClientConnect.mqttClients.get(clientId);
        try {
            mqttClientConnect.pub(topic, msg, qos);
        } catch (MqttException e) {
            log.error("publish error", e);
            throw new RuntimeException(e);
        }
    }
}
